package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AdminOrderMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.result.PageResult;
import com.sky.service.AdminOrderService;
import com.sky.vo.OrderDishVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class AdminOrderServiceImpl implements AdminOrderService {

    @Autowired
    private AdminOrderMapper adminOrderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        //开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        //查询语句

        //1、查找所有订单
        Page<OrderDishVO> orderDishVOS = new Page<>();

        List<Orders> orderslist = adminOrderMapper.getAllOrders(ordersPageQueryDTO);
        //2、将订单信息封装到VO中
        for (Orders orders : orderslist) {
            OrderDishVO orderDishVO = new OrderDishVO();
            BeanUtils.copyProperties(orders,orderDishVO);
            //3、查询对应订单的菜品信息
            List<OrderDetail> detaillist = orderDetailMapper.getDetailByOrderId(orders.getId());

            ArrayList<Object> dish = new ArrayList<>();
            for (OrderDetail orderDetail : detaillist) {
                //4、将菜品信息封装为一个字符串
                String name = orderDetail.getName();
                Integer number = orderDetail.getNumber();

                dish.add(name+"*"+number);

            }
            orderDishVO.setOrderDishes(String.valueOf(dish));
            orderDishVOS.add(orderDishVO);
        }

        //封装结果
        long total = orderDishVOS.getTotal();
        List<OrderDishVO> result = orderDishVOS.getResult();
        return new PageResult(total,result);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO getOrderNumberByStatus() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        //待派送数量
        List<Orders> orders1 = orderMapper.getOrdersByUserId(null, Orders.CONFIRMED);
        int size1 = orders1.size();
        orderStatisticsVO.setConfirmed(size1);
        //派送中数量
        List<Orders> orders2 = orderMapper.getOrdersByUserId(null, Orders.DELIVERY_IN_PROGRESS);
        int size2 = orders2.size();
        orderStatisticsVO.setDeliveryInProgress(size2);
        //待接单数量
        List<Orders> orders3 = orderMapper.getOrdersByUserId(null, Orders.REFUND);
        int size3 = orders3.size();
        orderStatisticsVO.setToBeConfirmed(size3);
        return orderStatisticsVO;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderById(Long id) {
        //1、查询orders表，将数据封装到orderVO中
        Orders orders = adminOrderMapper.getOrderById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        //2、查询order_detail表，得到一个集合，封装到VO中
        List<OrderDetail> orderDetailList = orderDetailMapper.getDetailByOrderId(orders.getId());
        orderVO.setOrderDetailList(orderDetailList);
        //3、返回VO
        return orderVO;
    }

    /**
     * 商家拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO ordersRejectionDTO) {
        //1、获取参数,查找对应订单
        Orders orders = adminOrderMapper.getOrderById(ordersRejectionDTO.getId());

        //判断状态
        if(orders.getPayStatus()==Orders.PAID && orders.getStatus()==Orders.TO_BE_CONFIRMED){
            //2、修改订单
            orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 商家接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //1、获取待接单信息
        Orders orders = adminOrderMapper.getOrderById(ordersConfirmDTO.getId());
        //2、判断订单状态
        if(orders.getPayStatus()==Orders.PAID && orders.getStatus()==Orders.TO_BE_CONFIRMED){
            //3、修改状态
            orders.setStatus(Orders.CONFIRMED);
            orderMapper.update(orders);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //1、获取订单
        Orders orders = adminOrderMapper.getOrderById(id);
        //2、判断状态
        if(orders.getPayStatus()==Orders.PAID && orders.getStatus()==Orders.CONFIRMED){
            //3、修改状态
            orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
            orderMapper.update(orders);
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        //1、获取订单
        Orders orders = adminOrderMapper.getOrderById(id);
        //2、判断状态
        if(orders.getPayStatus()==Orders.PAID && orders.getStatus()==Orders.DELIVERY_IN_PROGRESS){
            //3、修改状态
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        }else{
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        //1、获取订单
        Orders orders = adminOrderMapper.getOrderById(ordersCancelDTO.getId());
        //2、判断订单状态
        if(orders.getPayStatus()==Orders.PAID && (orders.getStatus()==Orders.CONFIRMED || orders.getStatus()==Orders.DELIVERY_IN_PROGRESS || orders.getStatus()==Orders.COMPLETED)){
            //3、修改订单状态并且退款
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason(ordersCancelDTO.getCancelReason());
            orderMapper.update(orders);

            log.warn("给用户退款");
        }else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

    }
}
